package com.xm.permission;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.widget.Button;
import android.os.Handler;
import android.os.Looper;
import android.text.method.ScrollingMovementMethod;

import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.graphics.Path;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;

public class MainActivity extends Activity {

    // 添加自己的TAG常量
    private static final String TAG = "AutoStartAccessibility";
    private TextView mStatusTextView;
    private Handler handler = new Handler(Looper.getMainLooper());
    
    private TextView tvGestureInfo;
    private TextView tvGestureHistory;
    private View touchOverlay;
    
    private StringBuilder gestureHistory = new StringBuilder();
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.tv_all_settings).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });

        mStatusTextView = findViewById(R.id.tv_status);

        // 初始化视图
        tvGestureInfo = findViewById(R.id.tvGestureInfo);
        tvGestureHistory = findViewById(R.id.tvGestureHistory);
        touchOverlay = findViewById(R.id.touchOverlay);
        
        // 设置历史记录可滚动
        tvGestureHistory.setMovementMethod(new ScrollingMovementMethod());

        // 自启动权限检查
        findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "点击第一个按钮");
                PermissionHelper.checkAndRequestAutoStartPermission(MainActivity.this, new PermissionCallback() {
                    @Override
                    public void onResult(boolean success, String tips) {
                        mStatusTextView.setText("是否有自启动权限:" + success+"\n提示：" + tips);
                    }
                });
            }
        });

        // 添加测试点击操作的按钮
        Button btnTestClick = findViewById(R.id.btnTestClick);
        btnTestClick.setOnClickListener(v -> testClick());

        // 添加测试滑动操作的按钮
        Button btnTestSwipe = findViewById(R.id.btnTestSwipe);
        btnTestSwipe.setOnClickListener(v -> testSwipe());
        
        // 添加检查无障碍服务状态的按钮
        Button btnCheckService = findViewById(R.id.btnCheckService);
        btnCheckService.setOnClickListener(v -> checkAccessibilityService());
        
    }

    private void testClick() {
        Log.i(TAG, "开始测试点击操作");
        
        // 检查无障碍服务是否开启
        if (!PermissionHelper.isAccessibilitySettingsOn(this)) {
            Log.w(TAG, "无障碍服务未开启，打开设置页面");
            Toast.makeText(this, "请先开启无障碍服务", Toast.LENGTH_SHORT).show();
            PermissionHelper.openAccessibilitySettings(this);
            return;
        }
        
        // 获取无障碍服务实例
        AutoStartAccessibilityService service = AutoStartAccessibilityService.getInstance();
        if (service == null) {
            Log.e(TAG, "无障碍服务未运行");
            Toast.makeText(this, "无障碍服务未运行，请先开启服务", Toast.LENGTH_SHORT).show();
            return;
        }

        // 测试点击屏幕中心位置
        int x = getResources().getDisplayMetrics().widthPixels / 2;
        int y = getResources().getDisplayMetrics().heightPixels / 2;
        
        // 更新状态提示
        mStatusTextView.setText("正在执行点击操作: " + x + ", " + y);
        Log.i(TAG, "执行点击操作，坐标: (" + x + ", " + y + ")");

        // 调用AccessibilityService执行点击
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 创建路径
            Path clickPath = new Path();
            clickPath.moveTo(x, y);

            // 创建手势描述
            GestureDescription.StrokeDescription clickStroke =
                    new GestureDescription.StrokeDescription(clickPath, 0, 100);

            GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
            gestureBuilder.addStroke(clickStroke);

            // 执行手势
            service.dispatchGesture(gestureBuilder.build(), new AccessibilityService.GestureResultCallback() {
                @Override
                public void onCompleted(GestureDescription gestureDescription) {
                    super.onCompleted(gestureDescription);
                    Log.i(TAG, "点击操作成功");
                    runOnUiThread(() -> {
                        mStatusTextView.setText("点击操作完成: 成功");
                        Toast.makeText(MainActivity.this, "点击成功", Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onCancelled(GestureDescription gestureDescription) {
                    super.onCancelled(gestureDescription);
                    Log.e(TAG, "点击操作被取消");
                    runOnUiThread(() -> {
                        mStatusTextView.setText("点击操作完成: 失败");
                        Toast.makeText(MainActivity.this, "点击失败", Toast.LENGTH_SHORT).show();
                    });
                }
            }, null);
        } else {
            mStatusTextView.setText("点击操作失败: 系统版本过低");
            Toast.makeText(this, "系统版本过低，不支持此操作", Toast.LENGTH_SHORT).show();
        }
    }

    private void testSwipe() {
        Log.i(TAG, "开始测试滑动操作");
        
        // 检查无障碍服务是否开启
        if (!PermissionHelper.isAccessibilitySettingsOn(this)) {
            Log.w(TAG, "无障碍服务未开启，打开设置页面");
            Toast.makeText(this, "请先开启无障碍服务", Toast.LENGTH_SHORT).show();
            PermissionHelper.openAccessibilitySettings(this);
            return;
        }

        performSwipeUp();
    }

    // 上划操作 - 从屏幕底部向上滑动
    private void performSwipeUp() {
        AutoStartAccessibilityService service = AutoStartAccessibilityService.getInstance();
        if (service == null) {
            Log.e(TAG, "无障碍服务未运行");
            Toast.makeText(this, "无障碍服务未运行", Toast.LENGTH_SHORT).show();
            return;
        }
        
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int screenHeight = getResources().getDisplayMetrics().heightPixels;
        
        int x1 = screenWidth / 2;
        int y1 = 10; // 接近屏幕底部
        int x2 = x1;
        int y2 = screenHeight / 2; // 滑动到屏幕中间
        
        mStatusTextView.setText("正在执行上划: " + x1 + "," + y1 + " → " + x2 + "," + y2);
        Log.i(TAG, "执行上划操作，从 (" + x1 + ", " + y1 + ") 到 (" + x2 + ", " + y2 + ")");
        
        performSwipeGesture(service, x1, y1, x2, y2, "上划");
    }

    // 返回上一页 - 从屏幕左侧向右滑动
    private void performSwipeBack() {
        AutoStartAccessibilityService service = AutoStartAccessibilityService.getInstance();
        if (service == null) {
            Log.e(TAG, "无障碍服务未运行");
            Toast.makeText(this, "无障碍服务未运行", Toast.LENGTH_SHORT).show();
            return;
        }
        
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int screenHeight = getResources().getDisplayMetrics().heightPixels;
        
        int x1 = 50; // 靠近屏幕左边缘
        int y1 = screenHeight / 2; // 屏幕中间高度
        int x2 = screenWidth / 3; // 滑动到屏幕1/3处
        int y2 = y1; // 保持相同高度
        
        mStatusTextView.setText("正在执行返回: " + x1 + "," + y1 + " → " + x2 + "," + y2);
        Log.i(TAG, "执行返回操作，从 (" + x1 + ", " + y1 + ") 到 (" + x2 + ", " + y2 + ")");
        
        performSwipeGesture(service, x1, y1, x2, y2, "返回");
    }

    // 最小化操作 - 从屏幕底部向上滑动后再向下
    private void performMinimize() {
        AutoStartAccessibilityService service = AutoStartAccessibilityService.getInstance();
        if (service == null) {
            Log.e(TAG, "无障碍服务未运行");
            Toast.makeText(this, "无障碍服务未运行", Toast.LENGTH_SHORT).show();
            return;
        }
        
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int screenHeight = getResources().getDisplayMetrics().heightPixels;
        
        // 先向上滑动一段距离
        int x1 = screenWidth / 2;
        int y1 = screenHeight - 100; // 接近屏幕底部
        int x2 = x1;
        int y2 = screenHeight / 2; // 滑动到屏幕中间
        
        mStatusTextView.setText("执行最小化(第一步): " + x1 + "," + y1 + " → " + x2 + "," + y2);
        Log.i(TAG, "执行最小化操作第一步，从 (" + x1 + ", " + y1 + ") 到 (" + x2 + ", " + y2 + ")");
        
        // 执行第一步滑动
        performSwipeGesture(service, x1, y1, x2, y2, "最小化第一步", () -> {
            // 第一步成功后执行第二步
            handler.postDelayed(() -> {
                // 向下滑动
                int x3 = x2;
                int y3 = y2;
                int x4 = x3;
                int y4 = screenHeight - 200; // 滑回接近底部
                
                mStatusTextView.setText("执行最小化(第二步): " + x3 + "," + y3 + " → " + x4 + "," + y4);
                Log.i(TAG, "执行最小化操作第二步，从 (" + x3 + ", " + y3 + ") 到 (" + x4 + ", " + y4 + ")");
                
                performSwipeGesture(service, x3, y3, x4, y4, "最小化第二步");
            }, 600);
        });
    }

    // 普通滑动 - 从屏幕下方向上滑动
    private void performNormalSwipe() {
        AutoStartAccessibilityService service = AutoStartAccessibilityService.getInstance();
        if (service == null) {
            Log.e(TAG, "无障碍服务未运行");
            Toast.makeText(this, "无障碍服务未运行", Toast.LENGTH_SHORT).show();
            return;
        }
        
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int screenHeight = getResources().getDisplayMetrics().heightPixels;
        
        int x1 = screenWidth / 2;
        int y1 = screenHeight * 3 / 4;
        int x2 = screenWidth / 2;
        int y2 = screenHeight / 4;
        
        mStatusTextView.setText("正在执行滑动: " + x1 + "," + y1 + " → " + x2 + "," + y2);
        Log.i(TAG, "执行普通滑动，从 (" + x1 + ", " + y1 + ") 到 (" + x2 + ", " + y2 + ")");
        
        performSwipeGesture(service, x1, y1, x2, y2, "普通滑动");
    }
    
    private void checkAccessibilityService() {
        Log.i(TAG, "检查无障碍服务状态");
        boolean isEnabled = PermissionHelper.isAccessibilitySettingsOn(this);
        Log.i(TAG, "无障碍服务状态: " + (isEnabled ? "已开启" : "未开启"));
        
        Toast.makeText(this, 
                "无障碍服务: " + (isEnabled ? "已开启" : "未开启，点击开启"), 
                Toast.LENGTH_SHORT).show();
        
        if (!isEnabled) {
            PermissionHelper.openAccessibilitySettings(this);
        }
    }

    /**
     * 处理触摸事件
     */
    private void handleTouchEvent(MotionEvent event) {
        int action = event.getActionMasked();
        float x = event.getX();
        float y = event.getY();
        int pointerCount = event.getPointerCount();
        
        String actionName;
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                actionName = "按下";
                break;
            case MotionEvent.ACTION_MOVE:
                actionName = "移动";
                break;
            case MotionEvent.ACTION_UP:
                actionName = "抬起";
                break;
            case MotionEvent.ACTION_CANCEL:
                actionName = "取消";
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                actionName = "多点按下";
                break;
            case MotionEvent.ACTION_POINTER_UP:
                actionName = "多点抬起";
                break;
            default:
                actionName = "其他(" + action + ")";
        }
        
        // 当前事件信息
        String currentInfo = String.format(Locale.getDefault(),
                "动作: %s, 坐标: (%.1f, %.1f), 点数: %d",
                actionName, x, y, pointerCount);
        
        // 更新显示
        tvGestureInfo.setText(currentInfo);
        
        // 不记录过多的MOVE事件以避免显示拥挤
        if (action != MotionEvent.ACTION_MOVE || event.getHistorySize() % 5 == 0) {
            // 添加到历史记录
            String timeStamp = timeFormat.format(new Date());
            String historyEntry = timeStamp + " - " + currentInfo + "\n";
            gestureHistory.insert(0, historyEntry); // 新事件插入到顶部
            
            // 限制历史记录长度
            if (gestureHistory.length() > 1500) {
                gestureHistory.setLength(1500);
            }
            
            tvGestureHistory.setText(gestureHistory.toString());
        }
        
        // 打印日志
        Log.d(TAG, "触摸事件: " + currentInfo);
        
        // 对于多点触控，打印每个触摸点的信息
        if (pointerCount > 1 && (action == MotionEvent.ACTION_POINTER_DOWN || 
                                 action == MotionEvent.ACTION_POINTER_UP)) {
            for (int i = 0; i < pointerCount; i++) {
                Log.d(TAG, String.format(Locale.getDefault(),
                        "触摸点 %d: 坐标: (%.1f, %.1f)", 
                        i, event.getX(i), event.getY(i)));
            }
        }
    }

    // 辅助方法：执行滑动手势
    private void performSwipeGesture(AccessibilityService service, float x1, float y1, float x2, float y2, String actionName) {
        performSwipeGesture(service, x1, y1, x2, y2, actionName, null);
    }

    // 辅助方法：执行滑动手势，带完成回调
    private void performSwipeGesture(AccessibilityService service, float x1, float y1, float x2, float y2, 
                                    String actionName, Runnable onComplete) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 添加日志标记开始执行滑动手势
            Log.d(TAG, "开始执行" + actionName + "手势: (" + x1 + "," + y1 + ") → (" + x2 + "," + y2 + ")");
            
            Path swipePath = new Path();
            swipePath.moveTo(x1, y1);
            swipePath.lineTo(x2, y2);
            
            // 增加滑动时间到800ms，提高滑动成功率
            GestureDescription.StrokeDescription swipeStroke = 
                    new GestureDescription.StrokeDescription(swipePath, 0, 800);
            
            GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
            gestureBuilder.addStroke(swipeStroke);
            
            final Handler mainHandler = new Handler(Looper.getMainLooper());
            boolean dispatchResult = service.dispatchGesture(gestureBuilder.build(), new AccessibilityService.GestureResultCallback() {
                @Override
                public void onCompleted(GestureDescription gestureDescription) {
                    super.onCompleted(gestureDescription);
                    // 直接记录日志，不依赖UI线程
                    Log.i(TAG, "★★★ " + actionName + "操作成功 ★★★");
                    
                    // 使用新的Handler确保UI更新在主线程执行
                    mainHandler.post(() -> {
                        mStatusTextView.setText(actionName + "操作完成: 成功");
                        Toast.makeText(MainActivity.this, actionName + "成功", Toast.LENGTH_SHORT).show();
                        
                        // 回调也使用Handler执行，避免嵌套问题
                        if (onComplete != null) {
                            mainHandler.post(onComplete);
                        }
                    });
                }

                @Override
                public void onCancelled(GestureDescription gestureDescription) {
                    super.onCancelled(gestureDescription);
                    Log.e(TAG, "XXX " + actionName + "操作被取消 XXX");
                    
                    mainHandler.post(() -> {
                        mStatusTextView.setText(actionName + "操作完成: 失败");
                        Toast.makeText(MainActivity.this, actionName + "失败", Toast.LENGTH_SHORT).show();
                    });
                }
            }, null);
            
            // 记录分发结果
            Log.d(TAG, actionName + "手势分发结果: " + (dispatchResult ? "成功" : "失败"));
            
            if (!dispatchResult) {
                mainHandler.post(() -> {
                    mStatusTextView.setText(actionName + "手势分发失败");
                    Toast.makeText(MainActivity.this, actionName + "分发失败", Toast.LENGTH_SHORT).show();
                });
            }
        } else {
            mStatusTextView.setText(actionName + "操作失败: 系统版本过低");
            Toast.makeText(this, "系统版本过低，不支持此操作", Toast.LENGTH_SHORT).show();
        }
    }
}